#include "McuDrivers/uart/uart.h"
#include "McuDrivers/system/system.h"
#include "McuDrivers/flash/DataRecord.h"
#include "McuDrivers/gpio/gpio.h"
#include "McuDrivers/timer/timer.h"
#include "McuDrivers/flash/FlashEEprom.h"

#include "Protocols/AfterBootloader.h"

uint8_t receiveData[12]={0},dataIndex=0;
void Uart_Tasks();

int main(void) 
{    
    
    /******** Initial ********/
    System_Initialize_g();
    Timer1_Initial_g();
    GPIO_Initial_g();
    Timer1_Start_g(10);

    Uart_Initial_g(115200);
    //InnerEEPromDataInit();
    System_Delay_MS_g(100);
    //Uart_Printf_g("AfterBootloader Initial");
    Uart_WriteBytes_g(g_AfterBootloader_ResetReponse,12);
    
    GPIO_LED_D3_Disable_g();
    GPIO_LED_D4_Disable_g();
    
    while(1)
    {
        //System_Delay_MS_g(1000);
        Uart_Tasks();
    }
    return 0;
}

uint16_t timerCount = 0;
void  Timer1CallBack()
{
    timerCount++;
    if(timerCount>50)
    {
        timerCount=0;
        GPIO_LED_D4_Toggle_g();
        GPIO_LED_D3_Toggle_g();
    }
}

void Uart_Tasks()
{
    if(U2STAbits.URXDA==1)
    {
        uint8_t tmp = Uart_ReadByte();
        switch(dataIndex)
        {
            case 0:
                if(tmp==g_AfterBootloader_Receive_StartFlag[0]) //起始标识1
                {
                    receiveData[0] = g_AfterBootloader_Receive_StartFlag[0];
                    dataIndex = 1;
                }
                else
                    dataIndex = 0;
                break;
            case 1:
                if(tmp==g_AfterBootloader_Receive_StartFlag[1]) //起始标识2
                {
                    receiveData[1] = g_AfterBootloader_Receive_StartFlag[1];
                    dataIndex = 2;
                }
                else
                    dataIndex = 0;
                break;
            case 10:
                if(tmp==g_AfterBootloader_Receive_EndFlag[0])
                {
                    receiveData[dataIndex] = g_AfterBootloader_Receive_EndFlag[0];
                    dataIndex = 11;
                }
                else
                    dataIndex = 0;
                break;
            case 11:
                if(tmp==g_AfterBootloader_Receive_EndFlag[1])
                {
                    receiveData[dataIndex] = g_AfterBootloader_Receive_EndFlag[1];
                    dataIndex = 0;
                    tmp = AfterBootloader_DataParse(receiveData,12);
                    Uart_WriteByte_g(tmp);
                    if(tmp==EntryBootloader) //进入Bootloader命令，相当于复位
                        SOFTWARE_RESET();
                }
                else
                    dataIndex = 0;
                break;
            default: 
                receiveData[dataIndex] = tmp; dataIndex++;
                break;
        }
    }
}